package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.DishFlavor;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;


/*
 * 菜品管理
 * */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 添加菜品
     * */

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());

        dishService.saveWithFlavor(dishDto);
        return R.success("添加菜品成功");
    }

    /**
     * 菜品分页查询
     * */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {

        //创建分页构造器
        //当前页码和每页条数（当前页码默认为1，每页条数默认为10）
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>(page,pageSize);

        //创建条件构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //设置查询条件
        lqw.like(name != null,Dish::getName,name);
        lqw.orderByDesc(Dish::getUpdateTime);

        //执行分页查询
        dishService.page(pageInfo,lqw);

        //对象拷贝 (除了records数据，该数据需要处理，然后设置)
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

        //获取records数据
        List<Dish> records = pageInfo.getRecords();

        //处理records数据
        List<DishDto> list = records.stream().map((item)->{
            DishDto dishDto = new DishDto();
            //将基本数据先拷贝过去
            BeanUtils.copyProperties(item,dishDto);
            //获取分类id
            Long categoryId = item.getCategoryId();
            //根据id获得菜品分类对象，然后获得分类名字
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String name1 = category.getName();
                dishDto.setCategoryName(name1);
            }

            return dishDto;
        }).collect(Collectors.toList());


        //将处理后的records数据赋值给dishDtoPage
        dishDtoPage.setRecords(list);


        return R.success(dishDtoPage);
    }

    /**
    * 根据id进行菜品查找
    * */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id) {

        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);

    }

    /**
    * 修改菜品信息
    * */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());

        dishService.updateWithFlavor(dishDto);

        return R.success("修改菜品成功");
    }

    /**
     * 在新增套餐中，根据条件查询菜品数据
     * */
    /*@GetMapping("/list")
    public R<List<Dish>> list(Dish dish) {
        log.info("Dish{}",dish);
        //创建条件构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //根据分类id进行查询展示
        lqw.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //添加查询条件，查询状态为1（起售）的菜品
        lqw.eq(Dish::getStatus,1);
        //排序条件
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);


        //调用查询
        List<Dish> list = dishService.list(lqw);

        return R.success(list);
    }*/

    /**
    * 可以按照菜品分类展示菜品（同时展示对应口味信息）
    * */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        log.info("Dish{}",dish);
        //创建条件构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //根据分类id进行查询展示
        lqw.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //添加查询条件，查询状态为1（起售）的菜品
        lqw.eq(Dish::getStatus,1);
        //排序条件
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        //调用查询
        List<Dish> list = dishService.list(lqw);

        //将数据拷贝进去
        List<DishDto> dishDtoList = list.stream().map((item)->{
            DishDto dishDto = new DishDto();
            //先将基本数据拷贝进去
            BeanUtils.copyProperties(item,dishDto);
            //根据菜品id查询对应的口味信息
            LambdaQueryWrapper<DishFlavor> flavorLqw = new LambdaQueryWrapper<>();
            flavorLqw.eq(DishFlavor::getDishId,item.getId());
            List<DishFlavor> dishFlavors = dishFlavorService.list(flavorLqw);

            //将对应的口味信息设置进去
            dishDto.setFlavors(dishFlavors);
            return dishDto;

        }).collect(Collectors.toList());

        return R.success(dishDtoList);
    }

    /**
    *删除菜品(批量删除，单个删除)
    * */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        log.info("ids{}",ids);
        dishService.removeWithFlavor(ids);
        return R.success("删除菜品成功");
    }

    /**
    * 批量停售
    * */
    @PostMapping("/status/0")
    public R<String> status(@RequestParam List<Long> ids) {
        log.info("ids:{}",ids);
        //创建条件构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.in(Dish::getId,ids)
        .eq(Dish::getStatus,1);
        //判断选中的商品是否有停用的商品
        int count = dishService.count(lqw);
        if (count > 0) {
            //获取所有选中的数据
            List<Dish> list = dishService.list(lqw);
            for (Dish dish : list) {
                dish.setStatus(0);
            }

            dishService.updateBatchById(list);
            return R.success("状态更改成功");
        }
        else {
            return R.error("选中的菜品中，无启用状态的菜品");
        }
    }

    /**
     * 批量起售
     * */
    @PostMapping("/status/1")
    public R<String> statusO(@RequestParam List<Long> ids) {
        log.info("ids:{}",ids);
        //创建条件构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.in(Dish::getId,ids)
                .eq(Dish::getStatus,0);
        //判断选中的商品是否有停用的商品
        int count = dishService.count(lqw);
        if (count > 0) {
            //获取所有选中的数据
            List<Dish> list = dishService.list(lqw);
            for (Dish dish : list) {
                dish.setStatus(1);
            }

            dishService.updateBatchById(list);
            return R.success("状态更改成功");
        }
        else {
            return R.error("选中的菜品中，无停用状态的菜品");
        }
    }


}
